package com.changgou.file.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.changgou.common.pojo.Result;
import com.changgou.common.pojo.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try {
            // 判断文件是否为空
            if (ObjectUtil.isEmpty(file)){
                throw new RuntimeException("文件不存在");
            }

            // 获取文件的完整名称
            String filename = file.getOriginalFilename();
            if (ObjectUtil.isEmpty(filename)){
                throw new RuntimeException("文件不存在");
            }
            // 获取文件扩展名
            String extName = StrUtil.subAfter(filename, ".", true);

            // 获取文件内容
            byte[] bytes = file.getBytes();

            // 创建文件上传实体类
            FastDFSFile fastDFSFile = new FastDFSFile(filename, bytes, extName);

            // 文件上传
            String[] upload = FastDFSClient.upload(fastDFSFile);

            // 封装返回结果
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true, StatusCode.OK,"文件上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}